import {
  computed,
  defineComponent,
  getCurrentInstance,
  nextTick,
  onMounted,
  reactive,
  ref,
  toRef,
  watch,
} from 'vue';

import _ from 'lodash';

import { dom, useQuasar } from '@teld/q-components';

import QSelect from '@teld/q-components/Select';
import { QItem, QItemSection } from '@teld/q-components/Item';
import QIcon from '@teld/q-components/Icon';
import TIcon from 't/basic/icon';
import TBtn from 't/basic/button';

import draggable from 't/third-party/vuedraggable';

import {
  commonProps,
  pickOwnForBasicComponent,
  usePropsTwoWayValues,
} from 't/common/utils';

export default defineComponent({
  directives: {
    removeTabindex: {
      mounted(el) {
        // 移除 tabindex 属性
        el?.removeAttribute('tabindex');
      },
    },
    enterClick: {
      mounted: function (el, binding) {
        // 添加点击事件监听器
        el?.addEventListener('keyup', function (event) {
          // 执行绑定的函数
          if (event.key === 'Enter') {
            // 在这里执行当按下 Enter 键时需要执行的逻辑
            // binding.value();
            typeof binding.value === 'function'
              ? binding.value()
              : event.target.click();
          }
        });
      },
    },
  },
  props: {
    columns: {
      type: Array,
      default() {
        return [];
      },
    },
    visibleColumns: {
      type: Array,
      default() {
        return [];
      },
    },
    items: {
      type: Array,
      default() {
        return [];
      },
    },
    isSort: {
      type: Boolean,
      default() {
        return false;
      },
    },
  },

  setup(props, { attrs, emit, expose, slots }) {
    const vm = getCurrentInstance();
    const $q = useQuasar();

    const twoWayProps = usePropsTwoWayValues(['items']);

    // const items = ref(
    //   _.map(props.items, item => {
    //     return { name: item, selected: true };
    //   }),
    // );

    const items = twoWayProps.items;

    const filterValue = ref('');
    const curValue = ref(null);

    const filterColumns = computed(() => {
      if (props.isSort) return props.columns;
      else
        return props.columns.filter(item => {
          // return false == itemsKeys.value.includes(item?.value);
          return true;
        });
    });

    const selectOpts = computed(() => {
      let selectItems = items.value.map(item => {
        return item.name;
      });
      _.remove(selectItems, curValue.value);

      return filterColumns.value.filter(item => {
        return (
          item.label &&
          item.label.includes(filterValue.value) &&
          !selectItems.includes(item.value)
        );
      });
    });

    const itemsKeys = computed(() => _.map(items.value, 'name'));

    const isVisibleColumn = cElement => {
      return _.includes(props.visibleColumns, cElement.value);
    };

    const remove = (array, index) => {
      // _.remove(array, item => item.name == element.name);
      array.splice(index, 1);
    };

    const selectedItem = element => {
      return _.find(props.columns, { value: element.name });
    };

    const slotItem = (element, index) => {
      return (
        <div class='row items-center' style='column-gap: 5px;'>
          <div class='col-auto' style='cursor: move'>
            {/* <TIcon name='fas icon-t-menu-unfold' /> */}
            <TIcon name='toc' />
          </div>
          <div class='col q-ml-sm tr-select-big'>
            <QSelect
              removeTabindex
              class={['tr-select-small']}
              dense
              // outlined
              use-input
              v-model={element.name}
              emit-value
              map-options
              fill-input
              hide-selected
              options-dense
              dropdown-icon={`${TComponents?.IconList?.common??'fas dx-icon'} ${TComponents?.IconList?.arrowDown??'icon-t-arrow-down'}`}
              borderless={true}
              options={selectOpts.value}
              onFilter={(value, doneFn) => {
                filterValue.value = value;
                curValue.value = element;
                doneFn();
              }}
              onKeydown={e => {
                if (e.key == 'Enter') {
                  clearFilter();
                }
              }}
              onPopupHide={() => {
                clearFilter();
              }}
            >
              {{
                option({ itemProps, opt, selected, toggleOption }) {
                  console.log('opt.value', itemsKeys.value.join(), opt.value);
                  return (
                    <QItem
                      onClick={() => {
                        clearFilter();
                      }}
                      style='color:rgba(0,0,0,var(--t-color-opacity,0.8));'
                      {...itemProps}
                      disable={
                        _.includes(itemsKeys.value, opt.value) && !selected
                      }
                    >
                      {props.isSort && (
                        <QItemSection avatar>
                          <QIcon
                            {...(isVisibleColumn(opt)
                              ? { color: 'primary', name: 'fas icon-t-eye' }
                              : { name: 'fas icon-t-eye-close' })}
                            // color={isVisibleColumn(opt) ? 'primary' : ''}
                            // name={`fas ${isVisibleColumn(opt) ? '' : 'icon-t-eye-close'}`}
                          />
                          {/* {isVisibleColumn(opt)} */}
                        </QItemSection>
                      )}
                      <QItemSection>{opt?.label}</QItemSection>
                    </QItem>
                  );
                },
              }}
            </QSelect>
          </div>
          {props.isSort && (
            <div class='col-auto'>
              <TIcon
                tabindex='0'
                // flat
                // round
                // icon='sort'

                // icon={`sort ${element.sortOrder == 'desc' ? 'dx-icon-sortdowntext' : 'dx-icon-sortuptext'}`}
                title={
                  element.sortOrder == 'desc'
                    ? $q.lang.dataGrid?.cmdColumn?.descTips
                    : $q.lang.dataGrid?.cmdColumn?.ascTips
                }
                name={
                  element.sortOrder == 'desc'
                    ? 'fas t-icon icon-t-sort-ascending fas-focus-visible'
                    : 'fas t-icon icon-t-sort-descending fas-focus-visible'
                }
                v-enterClick
                onClick={() => {
                  // alert(element.sort);
                  clearFilter();
                  element.sortOrder =
                    element.sortOrder == 'desc' ? 'asc' : 'desc';
                }}
              />
            </div>
          )}
          <div class='col-auto'>
            <TIcon
              tabindex='0'
              name='fas dx-icon icon-t-delete-outlined fas-focus-visible'
              v-enterClick
              onClick={() => {
                clearFilter();
                items.value.splice(index, 1);
              }}
            />
          </div>
        </div>
      );
    };

    const clearFilter = () => {
      filterValue.value = '';
      curValue.value = null;
    };

    return () => {
      return (
        <>
          {items.value.length > 0 && (
            <draggable
              style='display: flex;flex-direction: column;row-gap: 16px;margin-top:20px;'
              v-model={items.value}
              group='people'
              item-key='id'
              onStart={() => {
                clearFilter();
              }}
            >
              {{
                item({ element, index }) {
                  return slotItem(element, index);
                },
              }}
            </draggable>
          )}
          <TBtn
            v-removeTabindex
            style='margin-left: -12px;'
            label={$q.lang.dataGrid?.cmdColumn?.addColumn}
            icon='fas icon-t-plus'
            class='tr-button-text tr-button-dense q-mt-md'
            disable={items.value.length == filterColumns.value.length}
            onClick={() => items.value.push({ sortOrder: 'desc' })}
          ></TBtn>
        </>
      );
    };
  },
});
